﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ncp.Business;
using System.Linq.Expressions;
using ncp.Business.Common;

namespace ncp.Web.cms.work.HomeManager
{
    public partial class GenerateIndexPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(GenerateIndexPage));
        }

        //装载商品表视图
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public string BindTable()
        {
            string myWhere = "G_Status= 1 and CHARINDEX('h',G_Flag,0)>0";
            DataTable dt = GoodsInfoBll.GetGoodsInfoTable(myWhere, "G_Code", CommonConst.DB_Name);
            return JsonHelper.DataTableToJSON(dt);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                BuildIndexClass();
                //BuildIndex();
                var userInfo = WebMasterCookie.GetCookie(CommonConst.adminCookieName);
                Dictionary<string, object> dicHandleLog = new Dictionary<string, object>();
                dicHandleLog.Add("user_id", userInfo.Id);
                dicHandleLog.Add("computername", userInfo.Computername);
                dicHandleLog.Add("computerip", userInfo.Computerip);
                dicHandleLog.Add("handle_note", "生成行业分类");
                dicHandleLog.Add("obj_guid", "indexGoodsClass.htm");
                LogHandleBll.AddHandleLog(dicHandleLog, CommonConst.DB_Name);
                ClientScript.RegisterStartupScript(this.GetType(), "access", "alert('生成成功！')", true);
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "error", "alert('首页行业分类生成失败，请过会儿再试！')", true);
            }
            
        }

        //生成首页
        private void BuildIndex()
        {
            var url = HttpContext.Current.Request.Url.ToString().ToLower();
            int length = url.Length;
            int index = url.IndexOf("cms");
            var indexHtml = CommonBll.GetUrltoHtml(url.Substring(0,index) + "index.aspx");
            using (
                StreamWriter sw = new StreamWriter(Server.MapPath(Request.ApplicationPath) + "index.html", false,
                                                   System.Text.Encoding.UTF8))
            {
                sw.WriteLine(indexHtml);
                sw.Flush();
                sw.Close();
            }
        }

        //生成首页类别
        private void BuildIndexClass()
        {
            //保存地址
            var path = Server.MapPath(Request.ApplicationPath) + "uc/indexGoodsClass.htm";
            var tempPath = Server.MapPath(Request.ApplicationPath) + "templates/indexclass.html";
            string tempHtml = "";
            //读文件
            using (StreamReader sr = new StreamReader(tempPath, Encoding.GetEncoding("UTF-8")))//打开模板
            {
                tempHtml = sr.ReadToEnd();
                sr.Close();
            }
            tempHtml=tempHtml.Replace("{@content}", BuildHtml());
            //写文件
            using (StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.UTF8))
            {
                sw.WriteLine(tempHtml);
                sw.Flush();
                sw.Close();
            }
        }

        //生成html
        private string BuildHtml()
        {
            StringBuilder builder=new StringBuilder();
            //查询分类
            var dt = GoodsInfoBll.GetGoodsInfoTable("G_Status=1 and charindex('h',G_Flag)>0", "G_Id", CommonConst.DB_Name);
            var dtenu = dt.AsEnumerable();
            var level1 = (from a in dtenu
                          where a.Field<int>("gclevel")==2
                          select new
                                     {
                                         gcpid=a.Field<int>("gcpid"),
                                         gcid = a.Field<int>("GC_PId"),
                                         gcname = a.Field<string>("gcname")
                                     }).Distinct();
            foreach (var lev in level1)
            {
                builder.Append("<div class=\"con\">");
                builder.AppendFormat("<h4>{0}</h4>", lev.gcname);
                var lev1 = lev;
                var level2 = (from b in dtenu
                              where b.Field<int>("GC_Level") == 3 && b.Field<int>("GC_PId") == lev1.gcid
                              select new
                                         {
                                             gcid = b.Field<int>("GC_Id"),
                                             gcname = b.Field<string>("GC_Name")
                                         }).Distinct();
                foreach (var levClass in level2)
                {
                    builder.Append("<dl>");
                    builder.AppendFormat("<dt><a href=\"/products/{0}-{1}-{2}-0.html\">{3}:</a></dt>", lev.gcpid, lev.gcid,
                                         levClass.gcid, levClass.gcname);
                    var lev2 = levClass;
                    var level3 = (from c in dtenu
                                  where c.Field<int>("GC_Id") == lev2.gcid
                                  select new
                                             {
                                                 gId = c.Field<int>("G_Id"),
                                                 gName = c.Field<string>("G_Name")
                                             }
                                 ).Distinct();
                    if (level3.Count() > 0)
                    {
                        builder.Append("<dd>");
                        int i = 0;
                        foreach (var levInfo in level3)
                        {
                            builder.AppendFormat("<a href=\"/products/{0}-{1}-{2}-{3}.html\">{4}</a>", lev.gcpid, lev.gcid,
                                                 levClass.gcid, levInfo.gId, levInfo.gName);
                            if (i != level3.Count() - 1)
                            {
                                builder.Append("|");
                            }
                            i++;
                        }
                        builder.Append("</dd>");
                    }
                    builder.Append("<div class=\"bh-clear\"></div>");
                    builder.Append("</dl>");
                }
                builder.Append("<div class=\"bh-clear\"></div>");
                builder.Append("</div>");
            }
            return builder.ToString();
        }
    }
}
